<template>
  <view class="side-bar">
    <!-- 头像区域，点击跳转个人信息填写 -->
    <view class="avatar-box" @click="goPersonalInfo" style="cursor:pointer">
      <image class="avatar" :src="getAvatarSrc()" @error="onAvatarError" />
      <text class="avatar-name">{{ displayName }}</text>
    </view>
    <!-- 导航菜单 -->
    <view class="nav-list">
      <view class="nav-item nav-vertical" :class="{ active: currentTab === 'home' }" @click="handleTabClick('home')">
        <view class="nav-icon-circle">
          <uni-icons type="home" size="38" color="#1976ed" />
        </view>
        <text class="nav-text">首页</text>
      </view>
      <view class="nav-item nav-vertical" :class="{ active: currentTab === 'remind' }"
        @click="handleTabClick('remind')">
        <view class="nav-icon-circle">
          <uni-icons type="notification" size="38" color="#1976ed" />
        </view>
        <text class="nav-text">提醒</text>
      </view>
    </view>
    <!-- 设置按钮及弹出菜单容器 -->
    <view class="sidebar-setting-card setting-vertical">
      <view class="nav-item nav-vertical" :class="{ active: currentTab === 'setting' }" ref="settingBtnRef" @click="toggleSettingPopup">
        <view class="nav-icon-circle" ref="settingIconRef">
          <uni-icons type="gear-filled" size="34" color="#1976ed" />
        </view>
        <text class="nav-text">设置</text>
      </view>

      <teleport to="body">
        <view v-if="showSettingMenu" class="setting-mask" @click="closeSettingPopup"></view>
      </teleport>

      <teleport to="body">
        <view v-if="showSettingMenu" class="setting-popup setting-popup-fixed" :style="popupStyle" @click.stop>
          <view class="popup-arrow"></view>
          <view class="popup-setting-card popup-setting-card-light">
            <view class="popup-btn-row-horizontal">
              <!-- 密码修改按钮 -->
              <view class="popup-btn-col" @click="onPwd">
                <uni-icons type="locked" size="26" color="#222" />
                <text class="popup-btn-text popup-btn-text-dark">密码修改</text>
              </view>
              <!-- 分割线 -->
              <view class="popup-btn-divider"></view>
              <!-- 退出登录按钮 -->
              <view class="popup-btn-col" @click="onLogout">
                <uni-icons type="close" size="26" color="#222" />
                <text class="popup-btn-text popup-btn-text-dark">退出登录</text>
              </view>
            </view>
          </view>
        </view>
      </teleport>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick, onMounted, watch, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { go, replace } from '@/utils/nav.js';
import { getUserProfile } from '@/api/pc/elderly';
import { useUserStore } from '@/store/modules/user';
import { useRelativeStore } from '@/store/modules/relative';

const route = useRoute();
const showSettingMenu = ref(false);
const currentTab = ref('home');
const userStore = useUserStore();
const relativeStore = useRelativeStore();

// 显示姓名：优先使用画像 preferredName > name > userStore.name > ''
const displayName = ref('');
// 头像数据
const avatarData = ref(null);

async function fetchProfileName(uid) {
  if (!uid) return;

  // 使用缓存的用户画像，避免重复调用
  const res = await userStore.getUserProfileCached(uid);

  // 检查响应是否有效
  if (res && res.code === 200 && res.data) {
    const data = res.data;
    const prof = data;
    const name = prof?.name || userStore.name || '';
    displayName.value = name;

    // 保存头像数据
    if (prof?.personalPhotos && prof.personalPhotos.length > 0) {
      avatarData.value = prof.personalPhotos[0];
    }
  } else {
    // 用户画像不存在时，使用默认名称
    displayName.value = userStore.name || '';
  }
}

// 获取头像源
function getAvatarSrc() {
  if (avatarData.value?.fileBase64) {
    // 如果有base64头像数据，使用base64
    return `data:${avatarData.value.mimeType};base64,${avatarData.value.fileBase64}`;
  }
  // 否则使用默认头像
  return '/static/images/profile.jpg';
}

// 头像加载失败时的处理
function onAvatarError() {
  console.warn('头像加载失败，使用默认头像');
  // 可以在这里重置头像数据，强制使用默认头像
  avatarData.value = null;
}

const getTabFromPath = (path = '') => {
  if (path.includes('/remind')) return 'remind'
  if (path.includes('/passwordReset')) return 'setting'
  return 'home'
}

onMounted(() => {
  currentTab.value = getTabFromPath(route.path || route.fullPath || '')
  // 如果已有用户ID，加载画像姓名
  if (userStore.id) fetchProfileName(userStore.id);
})

watch(() => route.path, (p) => {
  currentTab.value = getTabFromPath(p || '')
})

// 监听用户ID变化（登录后）再取画像
watch(() => userStore.id, (id) => {
  if (id) {
    // 清除之前的头像数据和用户画像缓存，避免显示上一个账号的头像
    avatarData.value = null;
    displayName.value = '';
    userStore.clearUserProfileCache();
    fetchProfileName(id);
  } else {
    // 用户ID为空时，重置头像和姓名
    avatarData.value = null;
    displayName.value = '';
    userStore.clearUserProfileCache();
  }
});

// 监听全局头像更新事件
uni.$on('avatar-updated', (newAvatarData) => {
  console.log('收到头像更新事件:', newAvatarData);
  if (newAvatarData) {
    avatarData.value = newAvatarData;
    // 同时更新显示姓名（如果头像数据中包含姓名信息）
    if (newAvatarData.name) {
      displayName.value = newAvatarData.name;
    }
  }
});

// 监听用户画像缓存更新
watch(() => userStore.userProfile, (newProfile) => {
  if (newProfile && newProfile.data) {
    const data = newProfile.data;
    const name = data?.name || userStore.name || '';
    displayName.value = name;

    // 更新头像数据
    if (data?.personalPhotos && data.personalPhotos.length > 0) {
      avatarData.value = data.personalPhotos[0];
    }
  }
}, { deep: true });
const settingBtnRef = ref(null);
const settingIconRef = ref(null);
const popupStyle = ref({});

const emit = defineEmits(['tabChange']);
const handleTabClick = (tab) => {
  currentTab.value = tab;
  emit('tabChange', tab);
  if (tab === 'remind') {
    go('/pages/pc/remind');
  }
  if (tab === 'home') {
    go('/pages/pc/index');
  }
};

const goPersonalInfo = () => {
  go('/pages/pc/personalInfo');
};

let closeTimer = null;

function calcRect() {
  const iconEl = settingIconRef.value;
  const btnEl = settingBtnRef.value;
  let rect = null;
  try {
    rect = iconEl?.getBoundingClientRect ? iconEl.getBoundingClientRect() : (iconEl?.$el?.getBoundingClientRect ? iconEl.$el.getBoundingClientRect() : null);
    if (!rect) {
      rect = btnEl?.getBoundingClientRect ? btnEl.getBoundingClientRect() : (btnEl?.$el?.getBoundingClientRect ? btnEl.$el.getBoundingClientRect() : null);
    }
  } catch (e) { rect = null; }
  return rect;
}

const openSettingPopup = () => {
  if (closeTimer) { clearTimeout(closeTimer); closeTimer = null; }
  const rect = calcRect();
  const base = rect ? {
    position: 'fixed',
    left: rect.right + 12 + 'px',
    top: rect.top + rect.height / 2 + 'px',
    zIndex: 2000
  } : { position: 'fixed', left: '160px', top: '50%', zIndex: 2000 };
  popupStyle.value = { ...base, transform: 'translateY(-50%) translateX(-8px) scale(.9)', opacity: 0 };
  showSettingMenu.value = true;
  nextTick(() => {
    requestAnimationFrame(() => {
      popupStyle.value = { ...base, transform: 'translateY(-50%) translateX(0) scale(1)', opacity: 1 };
    });
  });
};

const closeSettingPopup = () => {
  if (!showSettingMenu.value) return;
  if (closeTimer) { clearTimeout(closeTimer); closeTimer = null; }
  popupStyle.value = { ...popupStyle.value, transform: 'translateY(-50%) translateX(-6px) scale(.94)', opacity: 0 };
  closeTimer = setTimeout(() => { showSettingMenu.value = false; }, 160);
};

const toggleSettingPopup = () => {
  handleTabClick('setting')
  if (showSettingMenu.value) closeSettingPopup(); else openSettingPopup();
};

onBeforeUnmount(() => {
  if (closeTimer) clearTimeout(closeTimer);
  // 移除事件监听
  uni.$off('avatar-updated');
});

const onPwd = () => {
  closeSettingPopup()
  go('/pages/pc/passwordReset');
  showSettingMenu.value = false;
};
const onLogout = () => {
  closeSettingPopup()
  uni.showModal({
    title: '确认退出',
    content: '退出后将清空登录状态并返回登录页',
    success: async (res) => {
      if (!res.confirm) return;
      try {
        await userStore.logOut();
      } catch (e) {
      }
      try {
        if (relativeStore?.$reset) relativeStore.$reset();
        else {
          relativeStore.setCurrentRelativeId && relativeStore.setCurrentRelativeId(null);
          relativeStore.list = [];
        }
      } catch (e) { }
      try {
        uni.$emit && uni.$emit('app-logout');
      } catch (e) { }
      showSettingMenu.value = false;
      replace('/pages/pc/login');
    }
  });
};
</script>

<style scoped>
.side-bar {
  width: 130px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 18px;
  box-shadow: 2px 0 16px 0 rgba(25, 118, 237, 0.08);
  position: relative;
  z-index: 10;
  height: 100vh;
  max-height: 100vh;
  overflow-y: auto;
  overflow-x: visible;
  flex: 0 0 130px;
  -webkit-overflow-scrolling: touch;
}

.avatar-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
  margin-top: 10px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 6px;
  border: 2px solid #fff;
}

.avatar-name {
  color: #fff;
  font-size: 14px;
  font-weight: 600;
}

.nav-list {
  flex: 1;
  width: 100%;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 38px;
}

.nav-item.nav-vertical {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #fff;
  opacity: 0.75;
  margin-bottom: 0;
  width: 100%;
  background: none;
  transition: background 0.2s, opacity 0.2s;
  padding: 0;
}

.nav-icon-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.28);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  transition: background 0.2s, box-shadow 0.2s, transform 0.2s;
}

.nav-item.nav-vertical.active .nav-icon-circle {
  background: #fff;
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.35);
  transform: scale(1.04);
}

.nav-item.nav-vertical.active uni-icons {
  color: #1976ed !important;
}

.nav-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 18px;
  margin: 0;
  padding: 0;
  text-align: center;
  font-weight: 600;
  letter-spacing: 1px;
}

.nav-item.nav-vertical.active .nav-text {
  color: #fff;
}

.nav-item.nav-vertical.active {
  opacity: 1;
}

.sidebar-setting-card.setting-vertical {
  position: sticky;
  bottom: 24px;
  margin-bottom: 48px;
  margin-top: auto;
}

.setting-mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 99;
  background: transparent;
}

.setting-popup {
  position: absolute;
  left: 100%;
  top: 50%;
  transform: translateY(-50%);
  margin-left: 12px;
  z-index: 1000;
  width: 220px;
  box-shadow: none;
  transition: transform .18s cubic-bezier(.22, .8, .36, 1), opacity .18s;
}

.setting-popup-fixed {
  position: fixed !important;
  left: auto;
  top: auto;
  margin-left: 0;
}

.black-text {
  color: #222 !important;
}

.popup-arrow {
  position: absolute;
  left: -5px;
  top: 50%;
  transform: translateY(-50%);
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-right: 10px solid #f7fbff;
  z-index: 101;
}

.popup-btn-col uni-icons {
  color: #222 !important;
}

.popup-setting-card {
  background: linear-gradient(180deg, #eaf4ff 0%, #ffffff 100%);
  border-radius: 10px;
  padding: 0;
  box-shadow: none;
}

.popup-btn-row-horizontal {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: center;
  height: 70px;
}

.popup-btn-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  cursor: pointer;
  padding: 0;
  height: 100%;
  transition: background 0.2s;
}

.popup-btn-col:hover {
  background: #e6eaf0;
  border-radius: 0 0 10px 10px;
}

.popup-btn-text-dark {
  margin-top: 6px;
  color: #222;
  text-align: center;
}

.popup-btn-divider {
  width: 1px;
  height: 40px;
  background: #e6eaf0;
  margin: auto 0;
  align-self: center;
}

@media (max-width: 900px) {
  .side-bar {
    width: 64px;
    flex: 0 0 64px;
  }

  .avatar-box {
    margin-bottom: 20px;
  }

  .avatar {
    width: 48px;
    height: 48px;
  }

  .avatar-name {
    /* display: none; */
  }

  .nav-list {
    gap: 22px;
  }

  .nav-icon-circle {
    width: 44px;
    height: 44px;
  }

  .nav-text,
  .sidebar-btn-text {
    /* display: none;  */
  }

  .setting-popup {
    left: 100%;
    margin-left: 8px;
  }
}

@media (max-width: 600px) {
  .side-bar {
    width: 56px;
    flex: 0 0 56px;
  }

  .nav-list {
    gap: 18px;
  }

  .nav-icon-circle {
    width: 40px;
    height: 40px;
  }
}
</style>

<style>
.popup-setting-card {
  font-size: clamp(13px, 0.9vw + 8px, 15px);
  line-height: 1.5;
  min-width: 180px;
  max-width: 240px;
  padding: 8px 12px !important;
  box-sizing: border-box;
  white-space: nowrap;
}

.popup-setting-card .popup-btn-row,
.popup-setting-card .popup-setting-btn-row {
  display: flex;
  align-items: center;
  gap: 6px;
}

.popup-setting-card .popup-btn-text,
.popup-setting-card .popup-setting-btn-text {
  font-size: inherit !important;
  line-height: 1.4;
  padding: 4px 6px;
  border-radius: 4px;
  transition: background .15s;
}

.popup-setting-card .popup-btn-text:hover,
.popup-setting-card .popup-setting-btn-text:hover {
  background: rgba(0, 0, 0, 0.04);
}

@media (max-width: 1380px) {
  .popup-setting-card {
    max-width: 210px;
    white-space: normal;
  }
}

@media (max-width: 1200px) {
  .popup-setting-card {
    font-size: clamp(12.5px, 1vw + 6px, 14px);
    padding: 10px 12px !important;
  }
}

@media (max-width: 1024px) {
  .popup-setting-card {
    max-width: 200px;
  }
}
</style>